package com.yirui.serialcomm.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author Dujie
 * @create 2025/8/8
 * @since 1.0.0
 */
public class ZipUtils {
    /**
     * 数据压缩
     * @param data
     * @return
     * @throws IOException
     */
    public static  byte[] compress(byte[] data) throws IOException {
        try(ByteArrayOutputStream out = new ByteArrayOutputStream();
            GZIPOutputStream gzip = new GZIPOutputStream(out)) {
            gzip.write(data);
            gzip.finish();
            return out.toByteArray();
        }

    }

    /**
     * 解压缩
     * @param data
     * @return
     * @throws IOException
     */
    public  static byte[] uncompress(byte[] data) throws IOException {
        try(ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayInputStream in = new ByteArrayInputStream(data);
            GZIPInputStream gunzip = new GZIPInputStream(in)) {
            byte[] buffer = new byte[512];
            int n;
            while ((n = gunzip.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
            out.flush();

            return out.toByteArray();
        }


    }

/*    public static void main(String[] args) throws IOException {
        String str = "{\"res\":[{\"server\":\"192.168.10.51\",\"name\":\"linphone\",\"talkStatus\":{\"audio\":{\"send\":{\"codec\":\"OPUS\",\"bandwidth\":\"19 kb/s\",\"rate\":\"48 k\",\"jitter\":\"0 ms\",\"tlost\":\"16777185\",\"plost\":\"99%\"},\"recv\":{\"codec\":\"OPUS\",\"bandwidth\":\"31 kb/s\",\"rate\":\"48 k\",\"jitter\":\"2 ms\",\"tlost\":\"34\",\"plost\":\"0%\"}},\"total\":{\"protocol\":\"SIP\",\"product\":\"Linphone Desktop/4.1.1 (belle-sip/1.6.3)\",\"recv\":\"32 kb/s\",\"send\":\"20 kb/s\"}}}],\"statusReason\":\"OK\",\"success\":true,\"responseTime\":16,\"totalTime\":16,\"callNum\":1,\"version\":\"2.0.0\",\"statusCode\":200}";
        System.out.println("原长度："+str.length());
        byte[] v = compress(str.getBytes());

        System.out.println("压缩长度："+v.length);
        String res = new String(Base64.getEncoder().encode(v));
        System.out.println("压缩后Base64："+res);
        System.out.println("压缩后Base64长度："+res.length());

        System.out.println("解压缩："+uncompress(compress(str.getBytes())));

        System.out.println("解压:"+HexUtils.toHexString(uncompress(HexUtils.fromHexString("1f8b08000000000000003310636264604c44070099adf98018000000"))));
    }*/
}
